<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Chapter extends Backend
{
    
    /**
     * Chapter模型对象
     * @var \app\admin\model\Chapter
     */
    protected $model = null;
    protected $searchFields = 'cchaptername';//默认按该字段模糊搜索

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Chapter;

        $categorylist = Db::name('category')->field('id,name')->select();
        $this->view->assign("categorylist", $categorylist);
    }

        /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['category'])
                ->where($where)
                ->order('updatetime desc')
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['category'])
                ->where($where)
                ->order('updatetime desc')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $row) {
                $row->visible(['id','createtime','weigh','icount','ichapterid','updatetime','cchaptername']);
                $row->visible(['category']);
                $row->getRelation('category')->visible(['name']);
            }

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

        /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $if_exist = Db::name('Chapter')->where(['ichapterid'=>$params['ichapterid']])->find();
                if(!empty($if_exist)){
                    $this->error('已经存在该ichapterid的章节，请勿重新添加');
                }

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }


    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();

            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {

                foreach ($list as $k => $v) {
                    $data = (array)json_decode($v,true);
                    $ichapterid = $data['ichapterid'];
                    $if_exist = Db::name('exam')->where(['ichapterid'=>$ichapterid])->find();
                    if(!empty($if_exist)){
                        $this->error('该章节存在试题，无法删除');
                    }
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $if_exist = Db::name('Chapter')->where(['ichapterid'=>$params['ichapterid'],'id'=>array('neq',$params['id'])])->find();
            if(!empty($if_exist)){
                $this->error('已经存在该ichapterid的章节，请勿重新添加');
            }
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    
    public function auto_chapter()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();

            $category_id = $data["category_id"];
            $file_path = $data['file'];
            $file_path = explode(',', $file_path);

            $count = 0;
            foreach($file_path as $file){
                
                $file = ltrim($file,'/');//需要去掉/不然说打不开图片
                $fp = fopen($file,"r");
                $str = fread($fp,filesize($file));//指定读取大小，这里把整个文件内容读取出来
                $str = str_replace("\r\n","<br />",$str);

                $array = json_decode($str,true);
                $now = count($array);
                $count = $count + $now;

                $now_desc_id = $desc_id = Db::name('chapter')->order('id desc')->value('id');
                foreach ($array as $key => $value) {
                    $now_desc_id += 1;
                    $value['weigh'] = $now_desc_id;
                    $value['category_id'] = $category_id;
                    $if_exist = Db::name('Chapter')->where(['ichapterid'=>$value['ichapterid']])->find();
                    if(!empty($if_exist)){
                        $this->error('已经存在该ichapterid的章节，请勿重新添加');
                    }
                    
                    $this->model->data($value,true)->allowField(true)->isUpdate(false)->save();
                }

            }

            $this->success('共插入'.$count.'条章节');
        }
        return $this->view->fetch();
    }
    

}
